#include "Event.h"
#include <iostream>

#ifdef _WIN32

Event::Event(bool state)
{
	this->_event = CreateEvent(NULL, true, state, NULL);
}

Event::~Event()
{
	CloseHandle(this->_event);
}

void	Event::Set()
{
	SetEvent(this->_event);
}

void	Event::Reset()
{
	ResetEvent(this->_event);
}

void	Event::Wait()
{
	WaitForSingleObject(this->_event, INFINITE);
}

#else

Event::Event(bool state) :
  _set(state)
{
	pthread_mutex_init(&_mutex, NULL);
	pthread_cond_init(&_cond, NULL);
}

Event::~Event()
{
	pthread_cond_destroy(&_cond);
	pthread_mutex_destroy(&_mutex);
}

void Event::Set()
{
	pthread_mutex_lock(&this->_mutex);
	_set = true;
	pthread_cond_broadcast(&this->_cond);
	pthread_mutex_unlock(&this->_mutex);
}

void Event::Reset()
{
    pthread_mutex_lock(&this->_mutex);
    _set = false;
    pthread_mutex_unlock(&this->_mutex);
}

void Event::Wait()
{
	pthread_mutex_lock(&this->_mutex);
	std::cout << "in wait lock" << std::endl;
	if (!_set)
    {
		std::cout << "waiting" << std::endl;
		pthread_cond_wait(&this->_cond, &this->_mutex);
    }
	pthread_mutex_unlock(&this->_mutex);
	std::cout << "waiting finished" << std::endl;
}

#endif
